package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.FollowMapper;
import com.hmdp.service.IFollowService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IUserService;
import com.hmdp.utils.UserHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {
    @Resource
    private IUserService userService;
    @Override
    public Result follow(Long followUserId, Boolean isFollow) {
        Long userId = UserHolder.getUser().getId();
        if (userId.equals(followUserId)) {
            throw new RuntimeException("不能关注自己");
        }
        if (isFollow) {
            //关注
            Follow follow = new Follow();
            follow.setUserId(userId);
            follow.setFollowUserId(followUserId);
            save(follow);
        } else {
            //取关
            remove(new QueryWrapper<Follow>().eq("user_id", userId).eq("follow_user_id", followUserId));
        }
        return Result.ok();
    }

    @Override
    public Result isFollow(Long followUserId) {
        // 判断用户是否关注
        Long userId = UserHolder.getUser().getId();
        Integer count = query().eq("user_id", userId).eq("follow_user_id", followUserId).count();
        return Result.ok(count > 0);
    }

    @Override
    public Result comments(Long userIdZ) {
        Long userId = UserHolder.getUser().getId();
        // 查询userID关注的所有用户ID，转换为Set集合
        Set<Long> userFollowSet = query().eq("user_id", userId).list()
                .stream().map(Follow::getFollowUserId)
                .collect(Collectors.toSet());
        // 查询userIdZ关注的所有用户ID，转换为Set集合
        Set<Long> userFollowZSet = query().eq("user_id", userIdZ).list()
                .stream().map(Follow::getFollowUserId)
                .collect(Collectors.toSet());
        // 取两者交集
        List<UserDTO> userDTOS = userFollowSet.stream()
                .filter(userFollowZSet::contains) // 过滤出在 userFollowZSet 中的元素
                .collect(Collectors.toList())
                        .stream().map(id -> {
                    User byId = userService.getById(id);
                    return BeanUtil.copyProperties(byId, UserDTO.class);
                }).collect(Collectors.toList());
        return Result.ok(userDTOS);
    }
}
